package jp.wug.util;

import java.io.IOException;
import java.io.Writer;

public class JsonWriter {
    boolean isFirst = true;
    Writer writer;
    JsonWriter child;

    public JsonWriter(Writer writer) throws IOException {
        this.writer = writer;
        writer.write("{");
    }

    public void close() throws IOException {
        prepare();
        writer.write("}");
        writer = null;
    }

    private void prepare() throws IOException {
        if (writer == null) {
            throw new IllegalStateException(
                    "This ModelWriter has already been closed.");
        }
        if (child != null) {
            child.close();
            child = null;
        }
    }

    private void write(String string) throws IOException {
        if (string == null) {
            writer.write("null");
        } else {
            writer.write("\"");
            writer.write(string.replace("\"", "\\\""));
            writer.write("\"");
        }
    }

    public void write(String name, String value) throws IOException {
        prepare();
        if (isFirst) {
            isFirst = false;
        } else {
            writer.write(",");
        }
        write(name);
        writer.write(":");
        write(value);
    }

    public void write(String name, boolean value) throws IOException {
        prepare();
        if (isFirst) {
            isFirst = false;
        } else {
            writer.write(",");
        }
        write(name);
        writer.write(":");
        writer.write(value ? "true" : "false");
    }

    public JsonWriter openChild(String name) throws IOException {
        prepare();
        if (isFirst) {
            isFirst = false;
        } else {
            writer.write(",");
        }
        write(name);
        writer.write(":");
        child = new JsonWriter(writer);
        return child;
    }
}